package com.yejing.urlconn;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class HttpURLConnectionDemo {

    private static final String CHARSET = "UTF-8";


    public static void main(String[] args) {
        HttpURLConnectionDemo demo = new HttpURLConnectionDemo();
        try {
//            String s1 = demo.testJson();
//            String s1 = demo.testForm();
            String s1 = demo.testGetTime();
            System.out.println(s1);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public String testJson() throws Exception {
        String url_s = "http://localhost:8889/demo/home/postjson";
        JSONObject json = new JSONObject();
        json.put("name", "叶静");
        json.put("age", 34);
        json.put("addr", "广东");
        String params = json.toJSONString();
        String result = doPostJson(url_s, params);
        return result;
    }

    public String testForm(){
        String url_s = "http://localhost:8889/demo/home/postForm";
        String params = "account=叶静&password=34&addr=广东";
        String result = doPostForm(url_s, params);
        return result;
    }

    public String testGet(){
        String url_s = "http://localhost:8889/demo/home/login?account=yejing&password=leegang";
        String result = doGet(url_s);
        return result;
    }

    public String testGetTime(){
        String url_s = "http://localhost:8889/demo/home/getTime?time=2016-11-29 11:11:11";
        String result = doGet(url_s);
        return result;
    }

    /**
     * get请求
     *
     * @param httpurl 请求路径
     * @return 请求结果
     * @author Gxf
     */
    public String doGet(String httpurl) {
        HttpURLConnection connection = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(httpurl);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            configRequest(connection, "GET", null, null);
            result = requestAndResponse(connection);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            connection.disconnect();// 关闭远程连接
        }
        return result;
    }

    /**
     * post 请求
     *
     * @param httpUrl 请求路径
     * @param param   请求参数
     * @return 请求返回结果
     * @author Gxf
     */
    public String doPostForm(String httpUrl, String param) {
        HttpURLConnection connection = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/x-www-form-urlencoded");
            configRequest(connection, "POST", headers, param);
            result = requestAndResponse(connection);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 断开与远程地址url的连接
            connection.disconnect();
        }
        return result;
    }


    /**
     * post 请求
     *
     * @param httpUrl 请求路径
     * @param param   请求参数
     * @return 请求返回结果
     * @author Gxf
     */
    public String doPostJson(String httpUrl, String param) {
        HttpURLConnection connection = null;
        String result = null;
        URL url = null;
        try {
            url = new URL(httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json;charset=utf-8;");
            configRequest(connection, "POST", headers, param);
            result = requestAndResponse(connection);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 断开与远程地址url的连接
            connection.disconnect();
        }
        return result;
    }

    private String requestAndResponse(HttpURLConnection connection) {
        InputStream is = null;
        BufferedReader br = null;
        String result = null;
        try {
            connection.connect();
            // 通过连接对象获取一个输入流，向远程读取
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, CHARSET));
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return result;
    }


    public void configRequest(HttpURLConnection conn,
                              String method,
                              HashMap<String, String> headers,
                              String params) throws IOException {
        // 设置连接请求方式
        conn.setRequestMethod(method);
        // 设置连接主机服务器超时时间：15000毫秒
        conn.setConnectTimeout(15000);
        // 设置读取主机服务器返回数据超时时间：60000毫秒
        conn.setReadTimeout(60000);

        // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
        conn.setDoOutput(true);
        // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
        conn.setDoInput(true);

        // 请求头
        if (headers != null && headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }

        // 请求参数
        if (null != params) {
            PrintWriter dos = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), CHARSET));
            dos.println(params);
            dos.flush();
            dos.close();
        }
    }

    /**
     * 处理https GET/POST请求 请求地址、请求方法、参数
     *
     * @param requestUrl    请求路径
     * @param requestMethod 请求方式 POST 或 GET
     * @param outputStr     写入的内容
     * @return 请求返回结果
     * @author Gxf
     */
    public String httpRequest(String requestUrl, String requestMethod, String outputStr) {
        StringBuffer buffer = null;
        try {
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod(requestMethod);
            //往服务器端写内容
            if (null != outputStr) {
                OutputStream os = conn.getOutputStream();
                os.write(outputStr.getBytes(CHARSET));
                os.close();
            }
            conn.connect();
            //读取服务器端返回的内容
            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, CHARSET);
            BufferedReader br = new BufferedReader(isr);
            buffer = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }


    /**
     * 处理https GET/POST请求 请求地址、请求方法、参数
     *
     * @param requestUrl    请求路径
     * @param requestMethod 请求方式 POST 或 GET
     * @param outputStr     写入的内容
     * @return 请求返回结果
     * @author Gxf
     */
    public String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        StringBuffer buffer = null;
        try {
            //创建SSLContext
            SSLContext sslContext = SSLContext.getInstance("SSL");
            TrustManager[] tm = {new MyX509TrustManager()};
            //初始化
            sslContext.init(null, tm, new java.security.SecureRandom());
            //获取SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod(requestMethod);
            //设置当前实例使用的SSLSoctetFactory
            conn.setSSLSocketFactory(ssf);
            conn.connect();
            //往服务器端写内容
            if (null != outputStr) {
                OutputStream os = conn.getOutputStream();
                os.write(outputStr.getBytes(CHARSET));
                os.close();
            }

            //读取服务器端返回的内容
            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, CHARSET);
            BufferedReader br = new BufferedReader(isr);
            buffer = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }
}
